# coding=utf-8
import arcpy
import os
import sys
import time
import traceback
from multiprocessing import Pool, cpu_count

# 设置默认编码为 UTF-8
try:
    reload(sys)
    sys.setdefaultencoding('utf-8')
except NameError:
    # Python 3 不需要此操作
    pass


# 配置参数
class Config:
    MDB_2019 = r"D:\ArcGis\DATA\19_test.mdb"
    MDB_2024 = r"D:\ArcGis\DATA\24_test.mdb"
    OUTPUT_FOLDER = r"D:\ArcGis\Output"
    OUTPUT_GDB = os.path.join(OUTPUT_FOLDER, "output_test.gdb")  # 合并输出到单个GDB

    # 要处理的要素类名称
    TARGET_FC = "DMGC_YQJSZKXX_polygon"  # 修改为面要素类名称

    # 对比字段配置
    FIELD_A = "ZKMC"  # 面名称字段，用于匹配
    FIELD_B = "Shape_Length"  # 用于计算相似度
    SIMILARITY_THRESHOLD = 0.9  # 相似度阈值

    # 是否打印详细的对比结果
    PRINT_DETAILED_COMPARISON = True
    # 打印详细对比结果的最大数量
    MAX_DETAILED_RESULTS = 200

    # 并行处理配置
    USE_PARALLEL = True  # 是否启用并行处理
    MAX_PROCESSES = max(1, cpu_count() - 1)  # 最大进程数


def create_gdb_if_not_exists(gdb_path):
    """创建文件地理数据库（如果不存在）"""
    try:
        if not arcpy.Exists(gdb_path):
            # 确保父目录存在
            parent_dir = os.path.dirname(gdb_path)
            if not os.path.exists(parent_dir):
                os.makedirs(parent_dir)
            arcpy.CreateFileGDB_management(os.path.dirname(gdb_path), os.path.basename(gdb_path))
            print("成功创建地理数据库: %s" % gdb_path)
        return True
    except Exception as e:
        print("创建地理数据库失败: %s, 错误: %s" % (gdb_path, str(e)))
        return False


def ensure_fields_with_z(feature_class, has_z=True, has_m=True):
    """确保要素类包含必要字段并支持Z/M值"""
    try:
        fields = [f.name.upper() for f in arcpy.ListFields(feature_class)]

        # 添加OLD_OBJECTID字段
        if "OLD_OBJECTID" not in fields:
            print("为要素类 %s 添加OLD_OBJECTID字段" % os.path.basename(feature_class))
            arcpy.AddField_management(feature_class, "OLD_OBJECTID", "LONG")
            with arcpy.da.UpdateCursor(feature_class, ["OBJECTID", "OLD_OBJECTID"]) as cursor:
                for row in cursor:
                    row[1] = row[0]
                    cursor.updateRow(row)

        # 添加STATE字段
        if "STATE" not in fields:
            print("为要素类 %s 添加STATE字段" % os.path.basename(feature_class))
            arcpy.AddField_management(feature_class, "STATE", "LONG")
            with arcpy.da.UpdateCursor(feature_class, ["STATE"]) as cursor:
                for row in cursor:
                    row[0] = 1  # 初始化为1（待判断）
                    cursor.updateRow(row)

        # 检查并启用Z/M值
        desc = arcpy.Describe(feature_class)
        if has_z and not desc.hasZ:
            print("警告: 要素类 %s 不支持Z值" % os.path.basename(feature_class))

        if has_m and not desc.hasM:
            print("警告: 要素类 %s 不支持M值" % os.path.basename(feature_class))

        return True
    except Exception as e:
        print("处理要素类字段失败: %s, 错误: %s" % (feature_class, str(e)))
        return False


def get_state_value(feature_class, object_id, field_name="STATE"):
    """查询要素类中指定OLD_OBJECTID的指定字段值"""
    try:
        with arcpy.da.SearchCursor(feature_class, [field_name], "OLD_OBJECTID = %d" % object_id) as cursor:
            for row in cursor:
                return row[0]
        return None
    except Exception as e:
        print("查询字段 %s 时出错: %s" % (field_name, str(e)))
        return None


def calculate_relative_error(value_2019, value_2024, threshold=0.1):
    """计算相对误差并返回相似度结果（0-1）或特殊标记（5）"""
    if value_2019 == 0 or value_2024 == 0:
        return 5  # 任意值为0时返回5，用于标记特殊状态

    # 计算相对误差（绝对值）
    relative_error = abs(value_2024 - value_2019) / max(abs(value_2019), abs(value_2024))
    # 转换为相似度（0-1，误差越小相似度越高）
    similarity = 1 - relative_error
    return similarity


def preload_data(feature_class, object_ids, fields, field_a, field_b):
    """预加载数据到内存字典，加速后续匹配"""
    data_dict = {}
    a_field_dict = {}  # 专门用于存储按A字段索引的映射

    for oid in object_ids:
        values = {}
        for field in fields:
            values[field] = get_state_value(feature_class, oid, field)
        data_dict[oid] = values

        # 特殊处理，添加按A字段索引的映射（用于快速查找）
        a_value = values.get(field_a)
        if a_value is not None:
            if a_value not in a_field_dict:
                a_field_dict[a_value] = []
            a_field_dict[a_value].append(oid)

    # 将A字段索引的映射合并到主字典
    data_dict.update(a_field_dict)
    return data_dict


def process_feature_class(fc):
    """处理单个要素类的主函数"""
    try:
        print("\n===== 开始处理要素类: %s =====" % fc)
        start_time = time.time()

        # 获取要素类完整路径
        fc_2019 = os.path.join(Config.MDB_2019, fc)
        fc_2024 = os.path.join(Config.MDB_2024, fc)

        # 检查要素类是否存在
        if not arcpy.Exists(fc_2019) or not arcpy.Exists(fc_2024):
            print("警告: 要素类 %s 或 %s 不存在" % (fc_2019, fc_2024))
            return False

        # 检查要素类是否支持Z/M值
        desc_2019 = arcpy.Describe(fc_2019)
        desc_2024 = arcpy.Describe(fc_2024)

        has_z = desc_2019.hasZ and desc_2024.hasZ
        has_m = desc_2019.hasM and desc_2024.hasM

        print("要素类 %s - Z值支持: %s, M值支持: %s" % (fc, has_z, has_m))

        # 存储对比结果
        comparison_results = []

        # ============== 第一次提取：处理STATE=2和STATE=3的数据 ==============
        # 获取2024年数据中STATE=2的记录（新增数据）
        new_ids_from_state2 = set()
        with arcpy.da.SearchCursor(fc_2024, ["OLD_OBJECTID", Config.FIELD_A, Config.FIELD_B]) as cursor:
            for row in cursor:
                old_objectid, a_value, b_value = row
                state = get_state_value(fc_2024, old_objectid)
                if state == 2:
                    new_ids_from_state2.add(old_objectid)
                    if Config.PRINT_DETAILED_COMPARISON and len(comparison_results) < Config.MAX_DETAILED_RESULTS:
                        comparison_results.append({
                            "type": "新增",
                            "name": a_value,
                            "value_2024": b_value
                        })
        print("  从STATE=2识别的新增记录: %d 条" % len(new_ids_from_state2))

        # 获取2019年数据中STATE=3的记录（消失数据）
        deleted_ids_from_state3 = set()
        with arcpy.da.SearchCursor(fc_2019, ["OLD_OBJECTID", Config.FIELD_A, Config.FIELD_B]) as cursor:
            for row in cursor:
                old_objectid, a_value, b_value = row
                state = get_state_value(fc_2019, old_objectid)
                if state == 3:
                    deleted_ids_from_state3.add(old_objectid)
                    if Config.PRINT_DETAILED_COMPARISON and len(comparison_results) < Config.MAX_DETAILED_RESULTS:
                        comparison_results.append({
                            "type": "消失",
                            "name": a_value,
                            "value_2019": b_value
                        })
        print("  从STATE=3识别的消失记录: %d 条" % len(deleted_ids_from_state3))

        # 确保输出GDB存在
        create_gdb_if_not_exists(Config.OUTPUT_GDB)

        # ============== 第二次提取：处理剩余STATE=1的数据 ==============
        # 获取2024年所有STATE=1的数据
        pending_2024_ids = []
        sql_2024_pending = "STATE = 1"
        with arcpy.da.SearchCursor(fc_2024, ["OLD_OBJECTID"]) as cursor:
            for row in cursor:
                pending_2024_ids.append(row[0])
        print("  2024年待处理记录(STATE=1): %d 条" % len(pending_2024_ids))

        # 获取2019年所有STATE=1的数据
        pending_2019_ids = []
        sql_2019_pending = "STATE = 1"
        with arcpy.da.SearchCursor(fc_2019, ["OLD_OBJECTID"]) as cursor:
            for row in cursor:
                pending_2019_ids.append(row[0])
        print("  2019年待处理记录(STATE=1): %d 条" % len(pending_2019_ids))

        # 预加载2019年数据到字典（按OLD_OBJECTID和A字段双重索引）
        print("  预加载2019年数据...")
        fields_2019 = ["OLD_OBJECTID", Config.FIELD_A, Config.FIELD_B]
        data_2019_dict = preload_data(fc_2019, pending_2019_ids, fields_2019, Config.FIELD_A, Config.FIELD_B)

        # 预加载2024年数据到字典（按OLD_OBJECTID和A字段双重索引）
        print("  预加载2024年数据...")
        fields_2024 = ["OLD_OBJECTID", Config.FIELD_A, Config.FIELD_B]
        data_2024_dict = preload_data(fc_2024, pending_2024_ids, fields_2024, Config.FIELD_A, Config.FIELD_B)

        # 处理2024年数据（按OLD_OBJECTID升序）
        print("  处理2024年数据...")
        for old_objectid_2024 in pending_2024_ids:
            # 从预加载的字典中获取数据
            data_2024 = data_2024_dict[old_objectid_2024]
            a_value_2024 = data_2024[Config.FIELD_A]
            b_value_2024 = data_2024[Config.FIELD_B]

            # 检查A字段是否为空
            if a_value_2024 is None or str(a_value_2024).strip() == "":
                with arcpy.da.UpdateCursor(fc_2024, ["STATE"], "OLD_OBJECTID = %d" % old_objectid_2024) as cursor:
                    for row in cursor:
                        row[0] = 5  # A字段为空，标记为5
                        cursor.updateRow(row)
                continue  # 跳过后续匹配逻辑

            # 标记是否找到匹配的19年记录
            matched_2019 = None

            # 直接通过A字段查找匹配的19年记录
            if a_value_2024 in data_2019_dict:
                matched_oids = data_2019_dict[a_value_2024]
                if matched_oids:
                    matched_oid = matched_oids[0]
                    matched_2019 = data_2019_dict[matched_oid]

            # 根据匹配结果设置STATE
            if matched_2019:
                b_value_2019 = matched_2019[Config.FIELD_B]
                similarity = calculate_relative_error(b_value_2019, b_value_2024, Config.SIMILARITY_THRESHOLD)

                state = 5 if similarity == 5 else (4 if similarity >= Config.SIMILARITY_THRESHOLD else 2)

                with arcpy.da.UpdateCursor(fc_2024, ["STATE"], "OLD_OBJECTID = %d" % old_objectid_2024) as cursor:
                    for row in cursor:
                        row[0] = state
                        cursor.updateRow(row)

                # 记录对比结果
                if Config.PRINT_DETAILED_COMPARISON and len(comparison_results) < Config.MAX_DETAILED_RESULTS:
                    comparison_results.append({
                        "type": "匹配" if state == 4 else "疑似新增",
                        "name": a_value_2024,
                        "value_2019": b_value_2019,
                        "value_2024": b_value_2024,
                        "similarity": similarity if similarity != 5 else None,
                        "state": state
                    })
            else:
                # 未找到A字段匹配的19年记录，标记为5
                with arcpy.da.UpdateCursor(fc_2024, ["STATE"], "OLD_OBJECTID = %d" % old_objectid_2024) as cursor:
                    for row in cursor:
                        row[0] = 5
                        cursor.updateRow(row)

        # 处理2019年数据（按OLD_OBJECTID升序） - 修改STATE=3为STATE=6
        print("  处理2019年数据...")
        for old_objectid_2019 in pending_2019_ids:
            # 从预加载的字典中获取数据
            data_2019 = data_2019_dict[old_objectid_2019]
            a_value_2019 = data_2019[Config.FIELD_A]
            b_value_2019 = data_2019[Config.FIELD_B]

            # 检查A字段是否为空
            if a_value_2019 is None or str(a_value_2019).strip() == "":
                with arcpy.da.UpdateCursor(fc_2019, ["STATE"], "OLD_OBJECTID = %d" % old_objectid_2019) as cursor:
                    for row in cursor:
                        row[0] = 5  # A字段为空，标记为5
                        cursor.updateRow(row)
                continue  # 跳过后续匹配逻辑

            # 标记是否找到匹配的24年记录
            matched_2024 = None

            # 直接通过A字段查找匹配的24年记录
            if a_value_2019 in data_2024_dict:
                matched_oids = data_2024_dict[a_value_2019]
                if matched_oids:
                    matched_oid = matched_oids[0]
                    matched_2024 = data_2024_dict[matched_oid]

            # 根据匹配结果设置STATE - 将原来的STATE=3改为STATE=6
            if matched_2024:
                b_value_2024 = matched_2024[Config.FIELD_B]
                similarity = calculate_relative_error(b_value_2019, b_value_2024, Config.SIMILARITY_THRESHOLD)

                state = 5 if similarity == 5 else (4 if similarity >= Config.SIMILARITY_THRESHOLD else 6)

                with arcpy.da.UpdateCursor(fc_2019, ["STATE"], "OLD_OBJECTID = %d" % old_objectid_2019) as cursor:
                    for row in cursor:
                        row[0] = state
                        cursor.updateRow(row)

                # 记录对比结果
                if Config.PRINT_DETAILED_COMPARISON and len(comparison_results) < Config.MAX_DETAILED_RESULTS:
                    comparison_results.append({
                        "type": "匹配" if state == 4 else "特殊状态6",
                        "name": a_value_2019,
                        "value_2019": b_value_2019,
                        "value_2024": b_value_2024,
                        "similarity": similarity if similarity != 5 else None,
                        "state": state
                    })
            else:
                # 未找到A字段匹配的24年记录，标记为5
                with arcpy.da.UpdateCursor(fc_2019, ["STATE"], "OLD_OBJECTID = %d" % old_objectid_2019) as cursor:
                    for row in cursor:
                        row[0] = 5
                        cursor.updateRow(row)

        # ============== 第三次提取：处理STATE=5和STATE=6的数据 ==============
        print("  处理STATE=5和STATE=6的数据...")

        # 获取2019年所有OLD_OBJECTID
        all_2019_oids = set()
        with arcpy.da.SearchCursor(fc_2019, ["OLD_OBJECTID"]) as cursor:
            for row in cursor:
                all_2019_oids.add(row[0])

        # 获取2024年所有OLD_OBJECTID
        all_2024_oids = set()
        with arcpy.da.SearchCursor(fc_2024, ["OLD_OBJECTID"]) as cursor:
            for row in cursor:
                all_2024_oids.add(row[0])

        # 处理2024年中STATE=5的数据
        state5_2024_ids = []
        with arcpy.da.SearchCursor(fc_2024, ["OLD_OBJECTID", Config.FIELD_A, Config.FIELD_B]) as cursor:
            for row in cursor:
                old_objectid, a_value, b_value = row
                state = get_state_value(fc_2024, old_objectid)
                if state == 5:
                    state5_2024_ids.append(old_objectid)
                    new_state = 2 if old_objectid not in all_2019_oids else 5
                    with arcpy.da.UpdateCursor(fc_2024, ["STATE"], "OLD_OBJECTID = %d" % old_objectid) as update_cursor:
                        for update_row in update_cursor:
                            update_row[0] = new_state
                            update_cursor.updateRow(update_row)

                    # 记录对比结果
                    if Config.PRINT_DETAILED_COMPARISON and len(comparison_results) < Config.MAX_DETAILED_RESULTS:
                        comparison_results.append({
                            "type": "新增" if new_state == 2 else "其他",
                            "name": a_value,
                            "value_2024": b_value
                        })

        # 处理2019年中STATE=5的数据（忽略STATE=6）
        state5_2019_ids = []
        with arcpy.da.SearchCursor(fc_2019, ["OLD_OBJECTID", Config.FIELD_A, Config.FIELD_B, "STATE"]) as cursor:
            for row in cursor:
                old_objectid, a_value, b_value, state = row
                if state == 5:
                    state5_2019_ids.append(old_objectid)

        # 处理STATE=5的记录
        for oid_2019 in state5_2019_ids:
            new_state = 3 if oid_2019 not in all_2024_oids else 5
            with arcpy.da.UpdateCursor(fc_2019, ["STATE"], "OLD_OBJECTID = %d" % oid_2019) as update_cursor:
                for update_row in update_cursor:
                    update_row[0] = new_state
                    update_cursor.updateRow(update_row)

        # 新增步骤1：用每一条19年STATE=5的数据去遍历24年STATE=5的数据
        # 若19年数据的OLD_OBJECTID在24年STATE=5的数据中出现，则将该19年数据的STATE值设为7
        print("  处理19年和24年STATE=5数据的匹配关系...")
        for oid_2019 in state5_2019_ids:
            if oid_2019 in state5_2024_ids:
                with arcpy.da.UpdateCursor(fc_2019, ["STATE"], "OLD_OBJECTID = %d" % oid_2019) as update_cursor:
                    for update_row in update_cursor:
                        update_row[0] = 7  # 将STATE设为7
                        update_cursor.updateRow(update_row)

                # 记录对比结果
                if Config.PRINT_DETAILED_COMPARISON and len(comparison_results) < Config.MAX_DETAILED_RESULTS:
                    # 获取该记录的名称和值
                    name = None
                    value_2019 = None
                    with arcpy.da.SearchCursor(fc_2019, [Config.FIELD_A, Config.FIELD_B],
                                               "OLD_OBJECTID = %d" % oid_2019) as search_cursor:
                        for search_row in search_cursor:
                            name, value_2019 = search_row
                            break
                    comparison_results.append({
                        "type": "状态7",
                        "name": name,
                        "value_2019": value_2019,
                        "description": "在2019年和2024年的STATE=5数据中均存在"
                    })

        # 新增步骤2：遍历2024年的STATE=5记录，检查是否存在于2019年的STATE=7记录中
        print("  处理24年STATE=5与19年STATE=7记录的相似度对比...")
        # 预加载2019年中STATE=7的记录
        state7_2019_data = {}
        with arcpy.da.SearchCursor(fc_2019, ["OLD_OBJECTID", Config.FIELD_B], "STATE = 7") as cursor:
            for row in cursor:
                oid, b_value = row
                state7_2019_data[oid] = b_value

        # 遍历2024年的STATE=5记录
        state5_2024_to_update = []
        with arcpy.da.SearchCursor(fc_2024, ["OLD_OBJECTID", Config.FIELD_B]) as cursor:
            for row in cursor:
                oid_2024, b_value_2024 = row
                state = get_state_value(fc_2024, oid_2024)
                if state == 5 and oid_2024 in state7_2019_data:
                    # 获取2019年STATE=7记录的B字段值
                    b_value_2019 = state7_2019_data[oid_2024]
                    # 计算相似度
                    similarity = calculate_relative_error(b_value_2019, b_value_2024, Config.SIMILARITY_THRESHOLD)
                    # 如果相似度高于等于阈值，将2024年记录的STATE设为6
                    if similarity >= Config.SIMILARITY_THRESHOLD and similarity != 5:
                        state5_2024_to_update.append((oid_2024, 6))
                        # 记录对比结果
                        if Config.PRINT_DETAILED_COMPARISON and len(comparison_results) < Config.MAX_DETAILED_RESULTS:
                            # 获取该记录的名称
                            name = None
                            with arcpy.da.SearchCursor(fc_2024, [Config.FIELD_A],
                                                       "OLD_OBJECTID = %d" % oid_2024) as name_cursor:
                                for name_row in name_cursor:
                                    name = name_row[0]
                                    break
                            comparison_results.append({
                                "type": "状态调整",
                                "name": name,
                                "value_2019": b_value_2019,
                                "value_2024": b_value_2024,
                                "similarity": similarity,
                                "new_state": 6,
                                "description": "与19年STATE=7记录相似度高于等于阈值"
                            })

        # 更新2024年记录的STATE值
        for oid, new_state in state5_2024_to_update:
            with arcpy.da.UpdateCursor(fc_2024, ["STATE"], "OLD_OBJECTID = %d" % oid) as update_cursor:
                for update_row in update_cursor:
                    update_row[0] = new_state
                    update_cursor.updateRow(update_row)

        # ============== 打印详细对比结果 ==============
        if Config.PRINT_DETAILED_COMPARISON and comparison_results:
            print("\n  === 详细对比结果 ===")
            print("  共记录 %d 条对比结果" % len(comparison_results))

            # 分类统计（排除STATE=6）
            type_counts = {}
            for result in comparison_results:
                result_type = result['type']
                if result_type != "特殊状态6":  # 排除STATE=6的记录
                    type_counts[result_type] = type_counts.get(result_type, 0) + 1

            # 打印分类统计结果
            print("\n  分类统计:")
            for result_type, count in type_counts.items():
                print("  - %s: %d 条" % (result_type, count))

            # 打印匹配记录的相似度统计
            match_results = [r for r in comparison_results if
                             r['type'] == '匹配' and 'similarity' in r and r['similarity'] is not None]
            if match_results:
                avg_similarity = sum(r['similarity'] for r in match_results) / len(match_results)
                max_similarity = max(r['similarity'] for r in match_results)
                min_similarity = min(r['similarity'] for r in match_results)

                print("\n  匹配记录相似度统计:")
                print("  - 平均相似度: %.4f" % avg_similarity)
                print("  - 最大相似度: %.4f" % max_similarity)
                print("  - 最小相似度: %.4f" % min_similarity)
                print("  - 相似度阈值: %s" % Config.SIMILARITY_THRESHOLD)
                print("  - 相似度达标率: %.2f%%" % (
                        sum(1 for r in match_results if r['similarity'] >= Config.SIMILARITY_THRESHOLD) / len(
                    match_results) * 100))

            # 打印详细结果（限制数量，排除STATE=6）
            print("\n  详细对比结果（前%d条）:" % min(Config.MAX_DETAILED_RESULTS, len(comparison_results)))
            for i, result in enumerate(comparison_results[:Config.MAX_DETAILED_RESULTS], 1):
                result_type = result['type']
                if result_type == "特殊状态6":  # 跳过STATE=6的记录
                    continue

                name = result['name']

                if result_type in ['匹配', '疑似新增']:
                    value_2019 = result['value_2019']
                    value_2024 = result['value_2024']
                    similarity = result['similarity']
                    state = result['state']
                    change = value_2024 - value_2019
                    change_percent = (change / value_2019 * 100) if value_2019 != 0 else float('inf')

                    print("  %d. %s - 名称: %s, "
                          "2019年值: %.4f, 2024年值: %.4f, "
                          "变化: %+.4f (%.2f%%), "
                          "相似度: %.4f, 状态: %d" % (i, result_type, name, value_2019, value_2024, change,
                                                      change_percent, similarity, state))
                elif result_type == '新增':
                    value_2024 = result['value_2024']
                    print("  %d. %s - 名称: %s, 2024年值: %.4f" % (i, result_type, name, value_2024))
                elif result_type == '消失':
                    value_2019 = result['value_2019']
                    print("  %d. %s - 名称: %s, 2019年值: %.4f" % (i, result_type, name, value_2019))
                elif result_type == '状态7':
                    value_2019 = result['value_2019']
                    description = result['description']
                    print("  %d. %s - 名称: %s, 2019年值: %.4f, 描述: %s" % (i, result_type, name, value_2019,
                                                                             description))
                elif result_type == '状态调整':
                    value_2019 = result['value_2019']
                    value_2024 = result['value_2024']
                    similarity = result['similarity']
                    new_state = result['new_state']
                    description = result['description']
                    change = value_2024 - value_2019
                    change_percent = (change / value_2019 * 100) if value_2019 != 0 else float('inf')
                    print("  %d. %s - 名称: %s, "
                          "2019年值: %.4f, 2024年值: %.4f, "
                          "变化: %+.4f (%.2f%%), "
                          "相似度: %.4f, 新状态: %d, 描述: %s" % (
                              i, result_type, name, value_2019, value_2024, change, change_percent, similarity,
                              new_state, description))
                else:
                    print("  %d. %s - 名称: %s" % (i, result_type, name))

        # ============== 输出最终结果 ==============
        print("\n  输出最终结果...")

        # 创建合并要素类的输出路径
        merged_fc_name = "%s_merged" % fc
        merged_fc_path = os.path.join(Config.OUTPUT_GDB, merged_fc_name)

        # 定义合并要素类的SQL查询 - 只输出STATE=2、3和5的数据
        sql_new = "STATE = 2"
        sql_deleted = "STATE = 3"
        sql_special_2024 = "STATE = 5"
        sql_special_2019 = "STATE = 5"

        # 创建临时要素集，用于存储合并结果
        temp_datasets = []

        # 导出2024年的新增数据到临时要素集
        temp_new_fc = os.path.join(Config.OUTPUT_GDB, "temp_%s_new" % fc)
        arcpy.FeatureClassToFeatureClass_conversion(
            in_features=fc_2024,
            out_path=Config.OUTPUT_GDB,
            out_name="temp_%s_new" % fc,
            where_clause=sql_new,
            config_keyword="ZANDM" if has_z and has_m else ""
        )
        temp_datasets.append(temp_new_fc)

        # 导出2019年的消失数据到临时要素集
        temp_deleted_fc = os.path.join(Config.OUTPUT_GDB, "temp_%s_deleted" % fc)
        arcpy.FeatureClassToFeatureClass_conversion(
            in_features=fc_2019,
            out_path=Config.OUTPUT_GDB,
            out_name="temp_%s_deleted" % fc,
            where_clause=sql_deleted,
            config_keyword="ZANDM" if has_z and has_m else ""
        )
        temp_datasets.append(temp_deleted_fc)

        # 导出2024年的特殊状态数据到临时要素集
        temp_special_2024_fc = os.path.join(Config.OUTPUT_GDB, "temp_%s_special_2024" % fc)
        arcpy.FeatureClassToFeatureClass_conversion(
            in_features=fc_2024,
            out_path=Config.OUTPUT_GDB,
            out_name="temp_%s_special_2024" % fc,
            where_clause=sql_special_2024,
            config_keyword="ZANDM" if has_z and has_m else ""
        )
        temp_datasets.append(temp_special_2024_fc)

        # 导出2019年的特殊状态数据到临时要素集
        temp_special_2019_fc = os.path.join(Config.OUTPUT_GDB, "temp_%s_special_2019" % fc)
        arcpy.FeatureClassToFeatureClass_conversion(
            in_features=fc_2019,
            out_path=Config.OUTPUT_GDB,
            out_name="temp_%s_special_2019" % fc,
            where_clause=sql_special_2019,
            config_keyword="ZANDM" if has_z and has_m else ""
        )
        temp_datasets.append(temp_special_2019_fc)

        # 合并所有临时要素集到一个最终要素类
        arcpy.Merge_management(temp_datasets, merged_fc_path)

        # 获取合并后要素类的记录数
        count_merged = int(arcpy.GetCount_management(merged_fc_path).getOutput(0))
        print("  已合并新增、消失和特殊状态记录到: %s" % merged_fc_path)
        print("  新增记录(STATE=2): %d 条" % len(new_ids_from_state2))
        print("  消失记录(STATE=3): %d 条" % len(deleted_ids_from_state3))
        print("  特殊状态记录(STATE=5): %d 条" % (len(state5_2024_ids) + len(state5_2019_ids)))
        print("  合并后总记录数: %d 条" % count_merged)

        # 清理临时要素集
        for temp_fc in temp_datasets:
            if arcpy.Exists(temp_fc):
                arcpy.Delete_management(temp_fc)

        end_time = time.time()
        print("  要素类 %s 处理完成，耗时: %.2f 秒" % (fc, end_time - start_time))
        return True

    except Exception as e:
        print("处理要素类 %s 时出错: %s" % (fc, str(e)))
        traceback.print_exc()
        return False


if __name__ == "__main__":
    try:
        print("===== 开始执行数据对比分析 =====")
        start_total_time = time.time()

        # 确保输出文件夹存在（兼容Python 2.7）
        if not os.path.exists(Config.OUTPUT_FOLDER):
            os.makedirs(Config.OUTPUT_FOLDER)

        # 设置地理处理环境
        arcpy.env.overwriteOutput = True

        # 收集2019年和2024年的指定要素类
        feature_classes_2019 = {}
        arcpy.env.workspace = Config.MDB_2019
        fc_2019 = os.path.join(Config.MDB_2019, Config.TARGET_FC)
        if arcpy.Exists(fc_2019) and ensure_fields_with_z(fc_2019):
            feature_classes_2019[Config.TARGET_FC] = fc_2019

        arcpy.env.workspace = Config.MDB_2024
        feature_classes_2024 = {}
        fc_2024 = os.path.join(Config.MDB_2024, Config.TARGET_FC)
        if arcpy.Exists(fc_2024) and ensure_fields_with_z(fc_2024):
            feature_classes_2024[Config.TARGET_FC] = fc_2024

        # 找出共同的要素类
        common_fcs = set(feature_classes_2019.keys()) & set(feature_classes_2024.keys())

        if not common_fcs:
            print("两个数据库中没有找到 %s 要素类！" % Config.TARGET_FC)
        else:
            print("找到 %d 个共同的 %s 要素类" % (len(common_fcs), Config.TARGET_FC))

            # 处理要素类（串行或并行）
            if Config.USE_PARALLEL and len(common_fcs) > 1:
                print("启用并行处理，使用 %d 个进程" % Config.MAX_PROCESSES)
                with Pool(processes=Config.MAX_PROCESSES) as pool:
                    results = pool.map(process_feature_class, common_fcs)

                # 输出结果统计
                success_count = sum(results)
                print("\n处理结果: %d/%d 个要素类成功处理" % (success_count, len(common_fcs)))
            else:
                print("使用串行处理")
                for fc in common_fcs:
                    process_feature_class(fc)

        end_total_time = time.time()
        print("\n===== 全部处理完成，总耗时: %.2f 秒 =====" % (end_total_time - start_total_time))

    except Exception as e:
        print("执行过程中发生错误: %s" % str(e))
        traceback.print_exc()
    finally:
        # 清理临时资源
        arcpy.ClearEnvironment("workspace")